#include <stdlib.h>
#include <stdbool.h>
#include "mystring.h"

int my_strlen(const char *str)
{
    const char *p = str;
    while (*p++)
        ;
    return (p - str - 1);
}

_Bool my_strcmp(const char *des, const char *src)
{
    int l1 = my_strlen(des);
    int l2 = my_strlen(src);

    if (l1 != l2) 
        return false;
    for (char* p1 = (char*)des, *p2 = (char*)src; p2 < (src + l1); ++p1, ++p2) {
        if (*p1 != *p2)
            return false;
    }
    return true;
}

void my_strcpy(char *des, char *src)
{
    while (*des++ = *src++)
        ;
}

void my_strcat(char *des, char *src)
{
    int des_len = my_strlen(des);
    int src_len = my_strlen(src);
    int total_len = des_len + src_len;

    for (int i = 0; i < src_len; ++i) {
        des[des_len + i] = src[i];
    }
    des[total_len] = '\0';
}

_Bool my_strstr(char *des, char *substr)
{
    int len = my_strlen(des);
    int slen = my_strlen(substr);
    bool flag = false;

    if (len < slen) return flag;

    for (int i = 0; i < (len - slen + 1); ++i) {
        for (int j = 0; j < slen; ++j) {
            if (substr[j] != des[j + i]) {
                break;
            }
            flag = true;
        }
        if (flag)
            break;
    }
    return flag;
}

char* my_strslice(char *str, int start, int end)
{
    int len = end - start + 1;
    if (end < start || (start > my_strlen(str) - len)) {
        return NULL;
    }
    char *buffer = (char*)calloc(1, sizeof(char) * (len + 1));
    for (int i = 0; i < len; ++i) {
        buffer[i] = str[start + i];
    }
    buffer[len] = '\0';

    return buffer;
}